import urllib.request
from http import cookiejar
filename = 'cookie.txt'
# 获取cookie
def get_cookie():
    # 实例化 cookie
    cookie = cookiejar.MozillaCookieJar(filename)
    # 创建handler
    handler = urllib.request.HTTPCookieProcessor(cookie)
    # 创建opener对象
    opener = urllib.request.build_opener(handler)
    # 请求网址
    url = ''
    resp = opener.open(url)
    # 保持cookie信息
    cookie.save()

def useCookie():
    # 实例化MozillaCookieJar
    cookie = cookiejar.MozillaCookieJar
    cookie.load(filename)
    print(cookie)


url = 'https://www.baidu.com'
header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36'}
proxyHandler = urllib.request.ProxyHandler({'https': 'https://127.0.0.1:7078', 'http': 'http://127.0.0.1:7078'})
# 设置代理
opener = urllib.request.build_opener(proxyHandler)
# 配置代理
install_opener = urllib.request.install_opener(opener)
# 设置请求头，请求地址
request = urllib.request.Request(url=url, headers=header, method='GET')
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))
